package drds.data_propagate.store;


import drds.data_propagate.common.utils.ToStringStyle;
import drds.data_propagate.entry.Entry;
import drds.data_propagate.entry.EntryType;
import drds.data_propagate.entry.EventType;
import drds.data_propagate.entry.Properties;
import drds.data_propagate.entry.position.SlavePosition;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

/**
 * store存储数据对象
 */
public class Event implements Serializable {

    private static final long serialVersionUID = 1333330351758762739L;
    @Setter
    @Getter
    private SlavePosition slaveId; // 记录数据产生的来源
    @Setter
    @Getter
    private Object rawEntry;
    @Setter
    @Getter
    private long executeTime;
    @Setter
    @Getter
    private EntryType entryType;
    @Setter
    @Getter
    private String journalName;
    @Setter
    @Getter
    private long position;
    @Setter
    @Getter
    private long serverId;
    @Setter
    @Getter
    private EventType eventType;
    @Setter
    @Getter
    private String gtid;
    @Setter
    @Getter
    private long rawLength;
    @Setter
    @Getter
    private int rowsCount;

    @Setter
    @Getter
    private Entry entry;

    public Event() {
    }

    public Event(SlavePosition slaveId, Entry entry) {
        this(slaveId, entry, true);
    }

    public Event(SlavePosition slaveId, Entry entry, boolean raw) {
        this.slaveId = slaveId;
        this.entryType = entry.getEntryType();
        this.executeTime = entry.getEntryHeader().getExecuteTimestamp();
        this.journalName = entry.getEntryHeader().getBinlogFileName();
        this.position = entry.getEntryHeader().getBinlogFileOffset();
        this.serverId = entry.getEntryHeader().getServerId();
        this.gtid = entry.getEntryHeader().getGtid();
        this.eventType = entry.getEntryHeader().getEventType();
        if (entryType == EntryType.row_data) {
            Properties props = entry.getEntryHeader().getProperties();
            if (props != null) {
                for (Properties.PropertyEntry p : props.getPropertyEntryList()) {
                    if ("rowsCount".equals(p.getKey())) {
                        rowsCount = Integer.parseInt((String) p.getValue());
                        break;
                    }
                }
            }
        }

        if (raw) {
            // build raw
            this.rawEntry = entry.getValue();
            this.rawLength = 0l;//今后进行计算 by czh
        } else {
            this.entry = entry;
            // 按照6倍的event length预估
            this.rawLength = entry.getEntryHeader().getEventLength() * 6;
        }
    }

    public String toString() {
        return ToStringStyle.toString(this);
    }

}
